package cn.tedu.luban.settle.webapi.service.impl;

import cn.tedu.luban.commons.pojo.order.dto.OrderMqDTO;
import cn.tedu.luban.settle.service.ISettleBillService;
import cn.tedu.luban.settle.service.ISettleEventService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SettleEventService implements ISettleEventService {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ISettleBillService settleBillService;

    @Value("${mq.topic.settle-success-topic:settle-success-topic}")
    private String orderSettleTopic;

    @Override
    public void sendSettledEvent(OrderMqDTO orderMqDTO) {
        log.info("发送消息给财务，财务打款,通知结算，通知订单");
        // 先修改结算状态
        try {
            TimeUnit.SECONDS.sleep(5L);
            // 执行结算状态的修改
            settleBillService.mockPayAndUpdateSettleBillStatus(orderMqDTO);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 再发消息给order模块表示订单流程完成
        rocketMQTemplate.asyncSend(orderSettleTopic, orderMqDTO, new SendCallback() {
            @Override
            public void onSuccess(SendResult result) {
                log.info("发送mq成功, topic: {}, result:{}", orderSettleTopic, result);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("发送mq失败, topic: {}, Throwable", orderSettleTopic, throwable);
            }
        });
    }
}
